package com.xjrsoft.module.oa.utils;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.xjrsoft.core.secure.utils.SecureUtil;
import com.xjrsoft.core.tool.utils.*;
import com.xjrsoft.module.base.entity.XjrBaseUser;
import com.xjrsoft.module.base.service.IXjrBaseUserService;
import com.xjrsoft.module.base.utils.DingtalkUtil;
import com.xjrsoft.module.base.utils.WeChatUtil;
import com.xjrsoft.module.login.utils.SmsKit;
import com.xjrsoft.module.oa.entity.XjrOaMessage;
import com.xjrsoft.module.oa.entity.XjrOaNews;
import com.xjrsoft.module.oa.entity.XjrOaSchedule;
import com.xjrsoft.module.oa.service.IXjrOaMessagestatusService;
import com.xjrsoft.module.workflow.entity.XjrNwfSchemeinfo;
import com.xjrsoft.module.workflow.service.IXjrNwfSchemeInfoService;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.task.api.TaskInfo;
import org.springframework.scheduling.annotation.Async;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Async
public class SendMessageUtil {

    private static IXjrOaMessagestatusService iXjrOaMessagestatusService;

    private static IXjrBaseUserService userService;

    private static IXjrNwfSchemeInfoService nwfSchemeInfoService;

    private static RuntimeService runtimeService;

    private static HistoryService historyService;

    private static DingtalkUtil dingtalkUtil;

    private static WeChatUtil weChatUtil;

    private static MailAccount account;


    static {
        nwfSchemeInfoService = SpringUtil.getBean(IXjrNwfSchemeInfoService.class);
        runtimeService = SpringUtil.getBean(RuntimeService.class);
        historyService = SpringUtil.getBean(HistoryService.class);
        iXjrOaMessagestatusService = SpringUtil.getBean(IXjrOaMessagestatusService.class);
        userService = SpringUtil.getBean(IXjrBaseUserService.class);
        dingtalkUtil = SpringUtil.getBean(DingtalkUtil.class);
        weChatUtil = SpringUtil.getBean(WeChatUtil.class);
        account = SpringUtil.getBean(MailAccount.class);
    }

    //添加新闻公告类消息
    public static void sendNewsMessage(XjrOaNews oaNews, Integer type) {
        XjrOaMessage xjrOaMessage = new XjrOaMessage();
        xjrOaMessage.setFtype(10);
        xjrOaMessage.setFlevel(12);
        xjrOaMessage.setModule(type);
        xjrOaMessage.setContent("您有一则新的通知《" + oaNews.getFullHead() + "》,请及时查看.");
        xjrOaMessage.setSendTime(new Date());
        xjrOaMessage.setDeleteMark(0);
        xjrOaMessage.setCreateDate(new Date());
        xjrOaMessage.setCreateUserId(SecureUtil.getUserId());
        xjrOaMessage.setLink(oaNews.getNewsId());
        iXjrOaMessagestatusService.addMessageStatus(xjrOaMessage, null);
    }

    //添加日程类消息
    public static void sendOaScheduleMessage(XjrOaSchedule oaSchedule) {
        XjrOaMessage xjrOaMessage = new XjrOaMessage();
        xjrOaMessage.setFtype(10);
        xjrOaMessage.setFlevel(12);
        xjrOaMessage.setModule(12);
        xjrOaMessage.setContent("您有一则新的日程《" + oaSchedule.getScheduleContent() + "》,请及时处理.");
        xjrOaMessage.setSendTime(new Date());
        xjrOaMessage.setDeleteMark(0);
        xjrOaMessage.setCreateDate(new Date());
        xjrOaMessage.setCreateUserId(SecureUtil.getUserId());
        xjrOaMessage.setLink(oaSchedule.getScheduleId());
        ArrayList<String> userIds = new ArrayList<>();
        userIds.add(SecureUtil.getUserId());
        iXjrOaMessagestatusService.addMessageStatus(xjrOaMessage, userIds);
    }

    //添加工作流类消息
    public static void sendWorkFlowMessage(TaskInfo task, String deploymentId, List<String> userIds, Integer type, List<Integer> messageSendTypes) throws Exception {
        String nwfSchemeInfoId = FlowableUtil.getNwfSchemeInfoIdByDepId(deploymentId);
        XjrNwfSchemeinfo xjrNwfSchemeinfo = nwfSchemeInfoService.getById(nwfSchemeInfoId);
        String name = xjrNwfSchemeinfo == null ? "" : xjrNwfSchemeinfo.getName();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String processInsId = task.getProcessInstanceId();
        XjrOaMessage xjrOaMessage = new XjrOaMessage();
        xjrOaMessage.setFtype(10);
        xjrOaMessage.setFlevel(12);
        xjrOaMessage.setSendTime(new Date());
        xjrOaMessage.setDeleteMark(0);
        xjrOaMessage.setCreateDate(new Date());
        xjrOaMessage.setCreateUserId(SecureUtil.getUserId());
        //审批或超时
        if (type == 1 || type == 4) {
            HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInsId).singleResult();
            XjrBaseUser startUser = userService.getById(processInstance.getStartUserId());
            String realName = startUser == null ? "" : startUser.getRealName();
            if (type == 1) {
                xjrOaMessage.setContent("您有一个" + realName + sdf.format(processInstance.getStartTime()) + "创建的《" + name + "》任务需要审批,请及时处理.");
            } else {
                xjrOaMessage.setContent("您有一个" + realName + sdf.format(processInstance.getStartTime()) + "创建的《" + name + "》任务已超时,请及时处理.");
                xjrOaMessage.setTaskId(task.getId());
                xjrOaMessage.setDeploymentId(deploymentId);
            }
            xjrOaMessage.setModule(13);
            xjrOaMessage.setLink("" + task.getId() + ";" + task.getName() + ";" + name + ";" + processInstance.getId() + ";" + DateUtil.formatDateTime(task.getCreateTime()) + ";" + processInstance.getStartUserId());
            if (CollectionUtil.isNotEmpty(messageSendTypes)) {
                for (Integer messageSendType : messageSendTypes) {
                    if (messageSendType == 10) {
                        iXjrOaMessagestatusService.addMessageStatus(xjrOaMessage, userIds);
                        List<XjrBaseUser> users = userService.listByIds(userIds);
                        if (CollectionUtil.isNotEmpty(users)) {
                            List<String> registrationIds = users.stream().filter(s -> StringUtil.isNotBlank(s.getRegistrationId())).map(s -> s.getRegistrationId()).collect(Collectors.toList());
                            JPushUtil.push(xjrOaMessage.getContent(), registrationIds,1);
                        }
                    }
                    if (messageSendType == 11) {
                        for (String userId : userIds) {
                            SmsKit.sendMessageByHuaWei(userService.getById(userId).getMobile(), xjrOaMessage.getContent());
                        }
                    }
                    if (messageSendType == 12) {
                        for (String userId : userIds) {
                            weChatUtil.sendMessage(xjrOaMessage, userService.getById(userId).getWeChatId());
                        }
                    }
                    if (messageSendType == 13) {
                        for (String userId : userIds) {
                            dingtalkUtil.sendMessage(xjrOaMessage, userService.getById(userId).getDingTalkId());
                        }
                    }
                    if (messageSendType == 14) {
                        //发送邮件
                        ArrayList<String> tos = CollUtil.newArrayList();
                        for (String userId : userIds) {
                            XjrBaseUser xjrBaseUser = userService.getById(userId);
                            if (xjrBaseUser != null) {
                                String email = xjrBaseUser.getEmail();
                                if (StringUtil.isNotBlank(email)) {
                                    tos.add(email);
                                }
                            }
                        }
                        if (CollectionUtil.isNotEmpty(tos) && account != null && xjrOaMessage != null) {
                            try {
                                MailUtil.send(account, tos, "xjrsoft消息提醒", xjrOaMessage.getContent(), false);
                            } catch (Exception e) {
                                throw new RuntimeException("邮箱配置信息错误!!");
                            }
                        }
                    }
                }
            }
        }
        //传阅
        if (type == 2) {
            HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
            XjrBaseUser startUser = userService.getById(processInstance.getStartUserId());
            String realName = startUser == null ? "" : startUser.getRealName();
            xjrOaMessage.setContent("您有一个" + realName + sdf.format(processInstance.getStartTime()) + "创建的《" + name + "》任务需要查看,请及时处理.");
            xjrOaMessage.setModule(14);
            xjrOaMessage.setLink("" + task.getId() + ";" + task.getName() + ";" + name + ";" + processInstance.getId() + ";" + DateUtil.formatDateTime(task.getCreateTime()) + ";" + processInstance.getStartUserId());
            if (CollectionUtil.isNotEmpty(messageSendTypes)) {
                for (Integer messageSendType : messageSendTypes) {
                    if (messageSendType == 10) {
                        iXjrOaMessagestatusService.addMessageStatus(xjrOaMessage, userIds);
                        List<XjrBaseUser> users = userService.listByIds(userIds);
                        if (CollectionUtil.isNotEmpty(users)) {
                            List<String> registrationIds = users.stream().filter(s -> StringUtil.isNotBlank(s.getRegistrationId())).map(s -> s.getRegistrationId()).collect(Collectors.toList());
                            JPushUtil.push(xjrOaMessage.getContent(), registrationIds,3);
                        }
                    }
                    if (messageSendType == 11) {
                        for (String userId : userIds) {
                            SmsKit.sendMessageByHuaWei(userService.getById(userId).getMobile(), xjrOaMessage.getContent());
                        }
                    }
                    if (messageSendType == 12) {
                        for (String userId : userIds) {
                            weChatUtil.sendMessage(xjrOaMessage, userService.getById(userId).getWeChatId());
                        }
                    }
                    if (messageSendType == 13) {
                        for (String userId : userIds) {
                            dingtalkUtil.sendMessage(xjrOaMessage, userService.getById(userId).getDingTalkId());
                        }
                    }
                    if (messageSendType == 14) {
                        //发送邮件
                        ArrayList<String> tos = CollUtil.newArrayList();
                        for (String userId : userIds) {
                            XjrBaseUser xjrBaseUser = userService.getById(userId);
                            if (xjrBaseUser != null) {
                                String email = xjrBaseUser.getEmail();
                                if (StringUtil.isNotBlank(email)) {
                                    tos.add(email);
                                }
                            }
                        }
                        if (CollectionUtil.isNotEmpty(tos) && account != null && xjrOaMessage != null) {
                            try {
                                MailUtil.send(account, tos, "xjrsoft消息提醒", xjrOaMessage.getContent(), false);
                            } catch (Exception e) {
                                throw new RuntimeException("邮箱发送账户配置错误!!");
                            }
                        }
                    }
                }
            }
        }
        //流程结束
        if (type == 3) {
            HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInsId).singleResult();
            xjrOaMessage.setContent("您" + sdf.format(processInstance.getStartTime()) + "创建的《" + name + "》任务已审批完成,请及时查看.");
            xjrOaMessage.setModule(16);
            xjrOaMessage.setLink("" + task.getId() + ";" + task.getName() + ";" + name + ";" + processInstance.getId() + ";" + DateUtil.formatDateTime(task.getCreateTime()) + ";" + processInstance.getStartUserId());
            if (CollectionUtil.isNotEmpty(messageSendTypes)) {
                for (Integer messageSendType : messageSendTypes) {
                    if (messageSendType == 10) {
                        iXjrOaMessagestatusService.addMessageStatus(xjrOaMessage, userIds);
                        List<XjrBaseUser> users = userService.listByIds(userIds);
                        if (CollectionUtil.isNotEmpty(users)) {
                            List<String> registrationIds = users.stream().filter(s -> StringUtil.isNotBlank(s.getRegistrationId())).map(s -> s.getRegistrationId()).collect(Collectors.toList());
                            JPushUtil.push(xjrOaMessage.getContent(), registrationIds,2);
                        }
                    }
                    if (messageSendType == 11) {
                        for (String userId : userIds) {
                            SmsKit.sendMessageByHuaWei(userService.getById(userId).getMobile(), xjrOaMessage.getContent());
                        }
                    }
                    if (messageSendType == 12) {
                        for (String userId : userIds) {
                            weChatUtil.sendMessage(xjrOaMessage, userService.getById(userId).getWeChatId());
                        }
                    }
                    if (messageSendType == 13) {
                        for (String userId : userIds) {
                            dingtalkUtil.sendMessage(xjrOaMessage, userService.getById(userId).getDingTalkId());
                        }
                    }
                    if (messageSendType == 14) {
                        //发送邮件
                        ArrayList<String> tos = CollUtil.newArrayList();
                        for (String userId : userIds) {
                            XjrBaseUser xjrBaseUser = userService.getById(userId);
                            if (xjrBaseUser != null) {
                                String email = xjrBaseUser.getEmail();
                                if (StringUtil.isNotBlank(email)) {
                                    tos.add(email);
                                }
                            }
                        }
                        if (CollectionUtil.isNotEmpty(tos) && account != null && xjrOaMessage != null) {
                            try {
                                MailUtil.send(account, tos, "xjrsoft消息提醒", xjrOaMessage.getContent(), false);
                            } catch (Exception e) {
                                throw new RuntimeException("邮箱发送账户配置错误!!");
                            }
                        }
                    }
                }
            }
        }
    }
}
